<template>
  <div class="container">
    <h3>vue+openlayers: 添加海量点，使用webGLPoint方式</h3>
    <h4>
      <el-button type="primary" size="mini" @click="showPoint">显示点</el-button>
      <el-button type="primary" size="mini" @click="clearLayer">清除图层</el-button>
    </h4>
    <div id="vue-openlayers"></div>
  </div>
</template>

<script>
import 'ol/ol.css';
import { Map, View } from 'ol';
import Tile from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import WebGLPointsLayer from 'ol/layer/WebGLPoints';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Feature from 'ol/Feature';
import { Point, LineString, Circle, Polygon } from 'ol/geom'; // 点、线、圆、面
import Style from 'ol/style/Style';
export default {
  data() {
    return {
      map: null,
      dataSource: new VectorSource({
        wrapX: false // 不连续显示
      }),
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      let layer = new Tile({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
        })
      })
      let feature_style = new WebGLPointsLayer({
        source: this.dataSource,
        style: this.featureStyle()
      })
      this.map = new Map({
        target: 'vue-openlayers',
        layers: [layer, feature_style],
        view: new View({
          center: [116.397411, 39.909186],
          zoom: 1,
          projection: 'EPSG:4326'
        })
      })
    },

    // 设置vector样式
    featureStyle() {
      let style = {
        symbol: {
          symbolType: 'image',
          size: 2,
          color: '#ff0000',
        }
      }
      return style;
    },

    // 清除vector数据源
    clearLayer() {
      this.dataSource.clear();
    },

    // 显示点
    showPoint() {
      for(let i = 0; i < 20000; i++) {
        let a = Math.floor(Math.random() *360) - 180; // 经度
        let b = Math.floor(Math.random() *180) - 90; // 纬度
        let pointFeature = new Feature({
          geometry: new Point([a, b]), // 点
        })
        this.dataSource.addFeature(pointFeature);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 750px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 100%;
      height: 720px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>
